package com.z.redis.command.impl;

import com.z.redis.RedisCore;
import com.z.redis.command.Command;
import com.z.redis.command.CommandType;
import com.z.redis.datatype.BytesWrapper;
import com.z.redis.resp.BulkString;
import com.z.redis.resp.Resp;
import com.z.redis.resp.RespArray;
import com.z.redis.util.TRACEID;
import io.netty.channel.ChannelHandlerContext;

import java.util.ArrayList;
import java.util.List;

/**
 * 实现了 config get database/*
 * CONFIG GET databases 命令用于获取当前 Redis 服务器支持的数据库数量
 * CONFIG GET * 命令用于获取当前 Redis 服务器的所有配置参数及其值
 */
public class Config implements Command {
    private String param;  // 存储配置参数名 ("database")
    @Override
    public CommandType type(){
        return CommandType.config;
    }

    @Override
    public void setContent(Resp[] array){
        if(array.length!=3){
            throw new IllegalArgumentException("ERR wrong number of arguments for 'config get' command");
        }
        String subCommand = ((BulkString) array[1]).getContent().toUTF8String();
        if(!subCommand.equalsIgnoreCase("get")){
            throw new IllegalArgumentException("ERR Unsupported CONFIG subcommand: " + subCommand);
        }
        param = ((BulkString)array[2]).getContent().toUTF8String();
    }

    @Override
    public void handle(ChannelHandlerContext ctx, RedisCore redisCore){
        if (param.equals("*") || param.equals("databases")) {
            List<BulkString> list = new ArrayList<>();
            list.add(new BulkString(new BytesWrapper("databases".getBytes(CHARSET))));
            list.add(new BulkString(new BytesWrapper("1".getBytes(CHARSET))));
            Resp[]    array  = list.toArray(new Resp[list.size()]);
            RespArray arrays = new RespArray(array);
            ctx.writeAndFlush(arrays);
        } else {
            String traceId = TRACEID.currentTraceId();
            LOGGER.debug("traceId:"+traceId+" 不识别的Config命令模式:"+param );
            ctx.channel().close();
        }
    }
}
